//
//  WBChooseView.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/12.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit


let WBChooseViewReuseIdentifier = "WBChooseViewReuseIdentifier"
let WBChooseViewItemMarin: CGFloat = 5

//MARK: - 代理传值添加图片
protocol WBChooseViewDelegate: NSObjectProtocol {

    func didChooseViewCellDelegateButtonClick(index:Int)
}

class WBChooseView: UICollectionView,UICollectionViewDataSource {

    //定义闭包
    var closure:(()->())?

     //定义一个数组来保存数据 作为数据源
    private lazy var images: [UIImage] = [UIImage]()
    //对外提供一个方法
    func addImage(image:UIImage){
       
       images.append(image)
        
        reloadData()
    }
    
    //提供一个方法供外界
    func getIamges() ->[UIImage] {
    
      return images
    }
    
    //布局属性
   private var flayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: flayout)

        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func  setupUI(){
        backgroundColor = RandomColor()
        delegate = self
        dataSource = self
        //注册cell
        registerClass(WBChooseViewCell.self, forCellWithReuseIdentifier: WBChooseViewReuseIdentifier)
        let itemWH = (WBUIScreenW - 2 * 10 - 2 * WBChooseViewItemMarin)/3
        
        flayout.itemSize = CGSize(width:itemWH, height: itemWH)
         flayout.minimumInteritemSpacing = WBChooseViewItemMarin
        flayout.minimumLineSpacing = WBChooseViewItemMarin
       
    }
    
}

//MARK: - 数据源方法UICollectionViewDataSource
extension  WBChooseView:WBChooseViewDelegate,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 {return 0}
        if images.count == 9 {return 9}
          return images.count + 1 //多一个显示添加按钮
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBChooseViewReuseIdentifier, forIndexPath: indexPath) as! WBChooseViewCell
        
        if indexPath.item == images.count {
            //不再取值 否则数组越界
           cell.image = nil
        }else {
        
          cell.image = images[indexPath.item]
        }
        
        cell.indexPath = indexPath
        
        cell.delegate = self
      return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //当用户点击最后一个加号按钮 执行闭包回调 添加图片
        if indexPath.item == images.count {
            //弹出视图
            //print("闭包弹出视图")
            closure?()
          
        }
        
    }
//    MARK: - cell的代理方法
    func didChooseViewCellDelegateButtonClick(index: Int) {
        //删除图片
        images.removeAtIndex(index)
        
        reloadData()
    }
    
}

//MARK: - 自定义cell
class WBChooseViewCell: UICollectionViewCell {

    //定义一个索引 在需要删除具体的cell图片时传递
    var indexPath: NSIndexPath?
    
     //代理属性
    weak var delegate: WBChooseViewDelegate?
    
  override  init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

  required init?(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
  }
   
    
    var image:UIImage? {
    
        didSet {
          
            if image == nil {  //显示加号
                bgImageView.image = UIImage(named: "compose_pic_add")
                
                //不显示删除按钮
                deleButton.hidden = true
            }else {
             
              //不经过压缩的方法直接拿到系统图片
              //bgImageView.image = image
                
             //去绘制图片 这样消耗小
              bgImageView.image = UIImage.getScalImage(image!)
               
                //设置按钮隐藏 不然cell重用导致 问题
                deleButton.hidden = false
            }
        
        }
    
    }
    
    
    
    private  func setupUI() {
       contentView.addSubview(bgImageView)
        
      contentView.addSubview(deleButton)
        
      bgImageView.snp_makeConstraints { (make) -> Void in
          make.edges.equalTo(contentView.snp_edges)
        }
        
        deleButton.snp_makeConstraints { (make) -> Void in
          make.right.equalTo(bgImageView.snp_right)
            make.top.equalTo(bgImageView.snp_top)
        }
    }
    
    //MARK: - 图片删除按钮点击
   @objc func deleButtonClick() {
    
      delegate?.didChooseViewCellDelegateButtonClick(indexPath!.item)
    
    }

    //MARK: - cell栏加载
    lazy var bgImageView: UIImageView = UIImageView()
    
  private  lazy var deleButton: UIButton = {
    
       let button = UIButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        button.sizeToFit()
        
        button.addTarget(self, action: "deleButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    
        return button
    }()

}
